package com.wwlwxg.dataStructure;


/**
 * 使用数组实现循环队列
 */
public class CircleArrayQueue {

	private Object[] elements;
	private static final int DEFAULT_CAPACITY = 10;
	private int size;
	private int head;
	private int tail;

	public CircleArrayQueue() {
		this(DEFAULT_CAPACITY);
	}

	public CircleArrayQueue(int size) {
		elements = new Object[size];
	}

	public static void main(String[] args) {
		CircleArrayQueue queue = new CircleArrayQueue(3);
		queue.add(1);
		queue.add(2);
		queue.pop();
		queue.add(3);
		queue.pop();
		queue.pop();
		queue.add(4);
	}

	/**
	 * 牺牲一个元素，当tail + 1 == head的时候，定义队列满，这是为了区分满和空
	 * @return
	 */
	public boolean isFull() {
		return head == (tail + 1) % elements.length;
	}

	/**
	 * 队列为空
	 * @return
	 */
	public boolean isEmpty() {
		return head == tail;
	}

	public boolean add(Object o) {
		if(isFull()) {
			System.out.println("队列满了");
			return false;
		}
		elements[tail] = o;
		System.out.println("添加队列 ");
		System.out.printf("elements[%d] = %d\n", tail, o);
		tail = (tail + 1) % elements.length;
		size++;
		return true;
	}

	public Object pop() {
		if(isEmpty()) {
			throw new RuntimeException("队列为空");
		}
		Object o = elements[head];
		System.out.println("取数据 ");
		System.out.printf("%d\n", o);
		head = (head + 1) % elements.length;
		size--;
		return o;
	}

	public int getSize() {
		return size;
	}

}
